package com.mk.api.open.controller;

import com.google.common.collect.Maps;
import com.sankuai.meituan.shangou.open.sdk.util.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;

/**
 * @Desc
 * @Author jiantongde
 * @Date 2022/8/16 15:29
 */
@Slf4j
public class BaseController {

    public static final String SIGN = "sig";

    public static final String DOMAIN = "http://101.42.175.35:8080";
    public static final String SECRETE = "f41cccab9218b9cae6be122eaaa5c02f";

    public boolean preHandle(HttpServletRequest request) throws Exception {
        /**
         * 心跳检测时会发送空包，能对空包做处理
         * 根据sig判断有没有传数据
         */
        String sign = request.getParameter(SIGN);
        if (StringUtils.isEmpty(sign)) {
            return false;
        }
        //预发环境不验证签名
//        if ("pre".equals(profileActive)) {
//            return true;
//        }
        Map<String, String> paramsMap = Maps.newHashMap();
        // 获取参数
        Map<String, String[]> map = request.getParameterMap();
        for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry) it.next();
            String key = (String) entry.getKey();
            String[] values = (String[]) entry.getValue();
            if (Objects.equals(SIGN, key)) {
                continue;
            }
            paramsMap.put(key, values[0]);
        }
        String url = DOMAIN + request.getRequestURI();
        String urlForGenSig = url + "?" + concatParams(paramsMap) + SECRETE;
        // 计算秘钥
        String selfSign = SignUtil.genSig(urlForGenSig);
        log.info("checkSign selfSign:{}, sign={}, 是否一致:{}", selfSign, sign, Objects.equals(sign, selfSign));
        /*if (!Objects.equals(sign, selfSign)) {
            log.error("mtBrand signVerification sign={}, selfSign={}, 参数={}", sign, selfSign, map);
            returnMsg(response);
            return false;
        }*/
        return true;
    }

    private String concatParams(Map<String, String> params) {
        Object[] keyArr = params.keySet().toArray();
        Arrays.sort(keyArr);
        StringBuffer sb = new StringBuffer();
        for (Object key : keyArr) {
            String val = params.get(key);
            sb.append("&").append(key).append("=").append(val);
        }
        String str = sb.toString().replaceFirst("&", "");
        return str;
    }
}
